<!DOCTYPE html>
<html lang="zh" dir="ltr" class="client-nojs">
<head>
<title>初始化</title>
<meta charset="UTF-8">
<meta name="generator" content="MediaWiki 1.21.2">
<link rel="shortcut icon" href="../../../common/favicon.ico">
<link rel="stylesheet" href="../../../common/ext.css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" href="../../../common/site_modules.css">
<style>a:lang(ar),a:lang(ckb),a:lang(fa),a:lang(kk-arab),a:lang(mzn),a:lang(ps),a:lang(ur){text-decoration:none}#toc{display:none}.editsection{display:none}
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-css:7:15cea3ec788a65b5187d4018eed543bf */</style>

<script src="../../../common/startup_scripts.js"></script>
<script>if(window.mw){
mw.config.set({"wgCanonicalNamespace":"","wgCanonicalSpecialPageName":false,"wgNamespaceNumber":0,"wgPageName":"cpp/language/initialization","wgTitle":"cpp/language/initialization","wgCurRevisionId":71351,"wgArticleId":8414,"wgIsArticle":true,"wgAction":"view","wgUserName":null,"wgUserGroups":["*"],"wgCategories":[],"wgBreakFrames":false,"wgPageContentLanguage":"zh","wgSeparatorTransformTable":["",""],"wgDigitTransformTable":["",""],"wgDefaultDateFormat":"zh","wgMonthNames":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgMonthNamesShort":["","1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],"wgRelevantPageName":"cpp/language/initialization","wgUserVariant":"zh","wgRestrictionEdit":[],"wgRestrictionMove":[]});
}</script><script>if(window.mw){
mw.loader.implement("user.options",function(){mw.user.options.set({"ccmeonemails":0,"cols":80,"date":"default","diffonly":0,"disablemail":0,"disablesuggest":0,"editfont":"default","editondblclick":0,"editsection":0,"editsectiononrightclick":0,"enotifminoredits":0,"enotifrevealaddr":0,"enotifusertalkpages":1,"enotifwatchlistpages":0,"extendwatchlist":0,"externaldiff":0,"externaleditor":0,"fancysig":0,"forceeditsummary":0,"gender":"unknown","hideminor":0,"hidepatrolled":0,"imagesize":2,"justify":0,"math":1,"minordefault":0,"newpageshidepatrolled":0,"nocache":0,"noconvertlink":0,"norollbackdiff":0,"numberheadings":0,"previewonfirst":0,"previewontop":1,"quickbar":5,"rcdays":7,"rclimit":50,"rememberpassword":0,"rows":25,"searchlimit":20,"showhiddencats":0,"showjumplinks":1,"shownumberswatching":1,"showtoc":0,"showtoolbar":1,"skin":"cppreference2","stubthreshold":0,"thumbsize":2,"underline":2,"uselivepreview":0,"usenewrc":0,"watchcreations":0,"watchdefault":0,"watchdeletion":0,
"watchlistdays":3,"watchlisthideanons":0,"watchlisthidebots":0,"watchlisthideliu":0,"watchlisthideminor":0,"watchlisthideown":0,"watchlisthidepatrolled":0,"watchmoves":0,"wllimit":250,"variant":"zh","language":"zh","searchNs0":true,"searchNs1":false,"searchNs2":false,"searchNs3":false,"searchNs4":false,"searchNs5":false,"searchNs6":false,"searchNs7":false,"searchNs8":false,"searchNs9":false,"searchNs10":false,"searchNs11":false,"searchNs12":false,"searchNs13":false,"searchNs14":false,"searchNs15":false,"gadget-MathJax":1,"gadget-ColiruCompiler":1});;},{},{});mw.loader.implement("user.tokens",function(){mw.user.tokens.set({"editToken":"+\\","patrolToken":false,"watchToken":false});;},{},{});
/* cache key: mwiki1-mwiki_zh_:resourceloader:filter:minify-js:7:258d7cd6aa9aa67dee25e01fb6a9e505 */
}</script>
<script>if(window.mw){
mw.loader.load(["mediawiki.page.startup","mediawiki.legacy.wikibits","mediawiki.legacy.ajax"]);
}</script>
<style type="text/css">/*<![CDATA[*/
.source-cpp {line-height: normal;}
.source-cpp li, .source-cpp pre {
	line-height: normal; border: 0px none white;
}
/**
 * GeSHi Dynamically Generated Stylesheet
 * --------------------------------------
 * Dynamically generated stylesheet for cpp
 * CSS class: source-cpp, CSS id: 
 * GeSHi (C) 2004 - 2007 Nigel McNie, 2007 - 2008 Benny Baumann
 * (http://qbnz.com/highlighter/ and http://geshi.org/)
 * --------------------------------------
 */
.cpp.source-cpp .de1, .cpp.source-cpp .de2 {font: normal normal 1em/1.2em monospace; margin:0; padding:0; background:none; vertical-align:top;}
.cpp.source-cpp  {font-family:monospace;}
.cpp.source-cpp .imp {font-weight: bold; color: red;}
.cpp.source-cpp li, .cpp.source-cpp .li1 {font-weight: normal; vertical-align:top;}
.cpp.source-cpp .ln {width:1px;text-align:right;margin:0;padding:0 2px;vertical-align:top;}
.cpp.source-cpp .li2 {font-weight: bold; vertical-align:top;}
.cpp.source-cpp .kw1 {color: #0000dd;}
.cpp.source-cpp .kw2 {color: #0000ff;}
.cpp.source-cpp .kw3 {color: #0000dd;}
.cpp.source-cpp .kw4 {color: #0000ff;}
.cpp.source-cpp .co1 {color: #909090;}
.cpp.source-cpp .co2 {color: #339900;}
.cpp.source-cpp .coMULTI {color: #ff0000; font-style: italic;}
.cpp.source-cpp .es0 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es1 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es2 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es3 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es4 {color: #008000; font-weight: bold;}
.cpp.source-cpp .es5 {color: #008000; font-weight: bold;}
.cpp.source-cpp .br0 {color: #008000;}
.cpp.source-cpp .sy0 {color: #008000;}
.cpp.source-cpp .sy1 {color: #000080;}
.cpp.source-cpp .sy2 {color: #000040;}
.cpp.source-cpp .sy3 {color: #000040;}
.cpp.source-cpp .sy4 {color: #008080;}
.cpp.source-cpp .st0 {color: #008000;}
.cpp.source-cpp .nu0 {color: #000080;}
.cpp.source-cpp .nu6 {color: #000080;}
.cpp.source-cpp .nu8 {color: #000080;}
.cpp.source-cpp .nu12 {color: #000080;}
.cpp.source-cpp .nu16 {color:#000080;}
.cpp.source-cpp .nu17 {color:#000080;}
.cpp.source-cpp .nu18 {color:#000080;}
.cpp.source-cpp .nu19 {color:#000080;}
.cpp.source-cpp .ln-xtra, .cpp.source-cpp li.ln-xtra, .cpp.source-cpp div.ln-xtra {background-color: #ffc;}
.cpp.source-cpp span.xtra { display:block; }

/*]]>*/
</style><!--[if lt IE 7]><style type="text/css">body{behavior:url("/mwiki/skins/cppreference2/csshover.min.htc")}</style><![endif]--></head>
<body class="mediawiki ltr sitedir-ltr ns-0 ns-subject page-cpp_language_initialization skin-cppreference2 action-view cpp-navbar">
        <!-- header -->
        <!-- /header -->
        <!-- content -->
<div id="cpp-content-base">
            <div id="content">
                <a id="top"></a>
                <div id="mw-js-message" style="display:none;"></div>
                                <!-- firstHeading -->
<h1 id="firstHeading" class="firstHeading">初始化</h1>
                <!-- /firstHeading -->
                <!-- bodyContent -->
                <div id="bodyContent">
                                        <!-- tagline -->
                    <div id="siteSub">来自cppreference.com</div>
                    <!-- /tagline -->
                                        <!-- subtitle -->
                    <div id="contentSub"><span class="subpages">&lt; <a href="../../cpp.html" title="cpp">cpp</a>‎ | <a href="../language.html" title="cpp/language">language</a></span></div>
                    <!-- /subtitle -->
                                                            <!-- bodycontent -->
                    <div id="mw-content-text" lang="zh" dir="ltr" class="mw-content-ltr"><div class="t-navbar" style=""><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../../cpp.html" title="cpp"> C++</a><div class="t-navbar-menu"><div><div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em">
<tr class="t-nv"><td colspan="5"> <a href="../language.html" title="cpp/language">语言</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../header.html" title="cpp/header">标准库头文件</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../freestanding.html" title="cpp/freestanding"> 自立与有宿主实现</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../named_req.html" title="cpp/named req">具名要求</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html#.E8.AF.AD.E8.A8.80.E6.94.AF.E6.8C.81" title="cpp/utility">语言支持库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../concepts.html" title="cpp/concepts">概念库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../error.html" title="cpp/error">诊断库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../utility.html" title="cpp/utility">工具库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../string.html" title="cpp/string">字符串库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../container.html" title="cpp/container">容器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../iterator.html" title="cpp/iterator">迭代器库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../ranges.html" title="cpp/ranges"> 范围库</a> <span class="t-mark-rev t-since-cxx20">(C++20)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../algorithm.html" title="cpp/algorithm">算法库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../numeric.html" title="cpp/numeric">数值库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../locale.html" title="cpp/locale">本地化库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../io.html" title="cpp/io">输入/输出库</a> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../filesystem.html" title="cpp/filesystem">文件系统库</a> <span class="t-mark-rev t-since-cxx17">(C++17)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../regex.html" title="cpp/regex">正则表达式库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../atomic.html" title="cpp/atomic">原子操作库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../thread.html" title="cpp/thread">线程支持库</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span> </td></tr>
<tr class="t-nv"><td colspan="5"> <a href="../experimental.html" title="cpp/experimental">技术规范</a> </td></tr>
</table></div><div></div></div></div></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><a href="../language.html" title="cpp/language">C++ 语言</a></div><div class="t-navbar-sep"> </div><div class="t-navbar-head"><strong class="selflink">初始化</strong><div class="t-navbar-menu"><div><div style="display:inline-block">
<div><table class="t-nv-begin" cellpadding="0" style="line-height:1.1em">
<tr class="t-nv-h2"><td colspan="5"><strong class="selflink">初始化器</strong></td></tr>
<tr class="t-nv"><td colspan="5"><a href="default_initialization.html" title="cpp/language/default initialization">默认初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="value_initialization.html" title="cpp/language/value initialization">值初始化</a> <span class="t-mark-rev t-since-cxx03">(C++03)</span></td></tr>
<tr class="t-nv"><td colspan="5"><a href="direct_initialization.html" title="cpp/language/direct initialization">直接初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="copy_initialization.html" title="cpp/language/copy initialization">复制初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="list_initialization.html" title="cpp/language/list initialization">列表初始化</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
<tr class="t-nv"><td colspan="5"><a href="aggregate_initialization.html" title="cpp/language/aggregate initialization">聚合初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="reference_initialization.html" title="cpp/language/reference initialization">引用初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="copy_elision.html" title="cpp/language/copy elision">复制消除</a></td></tr>
<tr class="t-nv-h2"><td colspan="5"><a href="initialization.html#.E9.9D.9E.E5.B1.80.E9.83.A8.E5.8F.98.E9.87.8F" title="cpp/language/initialization">静态初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="zero_initialization.html" title="cpp/language/zero initialization">零初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="constant_initialization.html" title="cpp/language/constant initialization">常量初始化</a></td></tr>
<tr class="t-nv-h2"><td colspan="5"><a href="initialization.html#.E5.8A.A8.E6.80.81.E5.88.9D.E5.A7.8B.E5.8C.96" title="cpp/language/initialization">动态非局部初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="initialization.html#.E5.8A.A8.E6.80.81.E5.88.9D.E5.A7.8B.E5.8C.96" title="cpp/language/initialization">有序动态初始化</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="initialization.html#.E5.8A.A8.E6.80.81.E5.88.9D.E5.A7.8B.E5.8C.96" title="cpp/language/initialization">无序动态初始化</a></td></tr>
<tr class="t-nv-h2"><td colspan="5">类成员初始化</td></tr>
<tr class="t-nv"><td colspan="5"><a href="initializer_list.html" title="cpp/language/initializer list" class="mw-redirect">成员初始化器列表</a></td></tr>
<tr class="t-nv"><td colspan="5"><a href="data_members.html#.E6.88.90.E5.91.98.E5.88.9D.E5.A7.8B.E5.8C.96" title="cpp/language/data members">默认成员初始化器</a> <span class="t-mark-rev t-since-cxx11">(C++11)</span></td></tr>
</table></div>
</div><div></div></div></div></div><div class="t-navbar-sep"> </div></div>
<p>变量的<i>初始化</i>在构造时提供其初值。
</p><p>初值可以由<a href="declarations.html" title="cpp/language/declarations">声明符</a>或 <a href="new.html" title="cpp/language/new">new 表达式</a>的初始化器部分提供。在函数调用时也会发生：函数形参及函数返回值也会被初始化。
</p><p>对于每个声明符，初始化器必须是下列之一：
</p>
<table class="t-sdsc-begin">

<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <code><b>(</b></code> <span class="t-spar">表达式列表</span> <code><b>)</b></code>
</td>
<td> (1)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <code><b>=</b></code> <span class="t-spar">表达式</span>
</td>
<td> (2)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr>
<tr class="t-sdsc">
<td> <code><b>{</b></code> <span class="t-spar">初始化器列表</span> <code><b>}</b></code>
</td>
<td> (3)
</td>
<td class="t-sdsc-nopad">
</td></tr>



<tr>
<td colspan="10" class="t-sdsc-sep">
</td></tr></table>
<div class="t-li1"><span class="t-li">1)</span> 括号中的以逗号分隔的含有任意表达式和花括号初始化器列表的列表</div>
<div class="t-li1"><span class="t-li">2)</span> 等号后面跟着一个表达式</div>
<div class="t-li1"><span class="t-li">3)</span> 花括号初始化器列表：以逗号分隔且可以为空的含有表达式和其他花括号初始化器列表的列表</div>
<p>根据上下文，初始化器可以调用：
</p>
<ul><li> <a href="value_initialization.html" title="cpp/language/value initialization">值初始化</a>，例如 <span class="t-c"><span class="mw-geshi cpp source-cpp"><a href="../string/basic_string.html"><span class="kw1230">std::<span class="me2">string</span></span></a> s<span class="br0">{</span><span class="br0">}</span><span class="sy4">;</span></span></span>
</li><li> <a href="direct_initialization.html" title="cpp/language/direct initialization">直接初始化</a>，例如 <span class="t-c"><span class="mw-geshi cpp source-cpp"><a href="../string/basic_string.html"><span class="kw1230">std::<span class="me2">string</span></span></a> s<span class="br0">(</span><span class="st0">"hello"</span><span class="br0">)</span><span class="sy4">;</span></span></span>
</li><li> <a href="copy_initialization.html" title="cpp/language/copy initialization">复制初始化</a>，例如 <span class="t-c"><span class="mw-geshi cpp source-cpp"><a href="../string/basic_string.html"><span class="kw1230">std::<span class="me2">string</span></span></a> s <span class="sy1">=</span> <span class="st0">"hello"</span><span class="sy4">;</span></span></span>
</li><li> <a href="list_initialization.html" title="cpp/language/list initialization">列表初始化</a>，例如 <span class="t-c"><span class="mw-geshi cpp source-cpp"><a href="../string/basic_string.html"><span class="kw1230">std::<span class="me2">string</span></span></a> s<span class="br0">{</span><span class="st0">'a'</span>, <span class="st0">'b'</span>, <span class="st0">'c'</span><span class="br0">}</span><span class="sy4">;</span></span></span>
</li><li> <a href="aggregate_initialization.html" title="cpp/language/aggregate initialization">聚合初始化</a>，例如 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">char</span> a<span class="br0">[</span><span class="nu0">3</span><span class="br0">]</span> <span class="sy1">=</span> <span class="br0">{</span><span class="st0">'a'</span>, <span class="st0">'b'</span><span class="br0">}</span><span class="sy4">;</span></span></span>
</li><li> <a href="reference_initialization.html" title="cpp/language/reference initialization">引用初始化</a>，例如 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">char</span><span class="sy3">&amp;</span> c <span class="sy1">=</span> a<span class="br0">[</span><span class="nu0">0</span><span class="br0">]</span><span class="sy4">;</span></span></span>
</li></ul>
<p>如果不提供初始化器，那么<a href="default_initialization.html" title="cpp/language/default initialization">默认初始化</a>的规则会被应用。
</p>
<h3><span class="mw-headline" id=".E9.9D.9E.E5.B1.80.E9.83.A8.E5.8F.98.E9.87.8F">非局部变量</span></h3>
<p>所有具有静态<a href="storage_duration.html" title="cpp/language/storage duration">存储期</a>的非局部变量的初始化会作为程序启动的一部分在 <a href="main_function.html" title="cpp/language/main function">main 函数</a>的执行之前进行（除非被延迟，见下文）。所有具有线程局部存储期的非局部变量的初始化会作为线程启动的一部分进行，按顺序早于线程函数的执行开始。对于这两种变量，初始化发生于两个截然不同的阶段：
</p>
<h4><span class="mw-headline" id=".E9.9D.99.E6.80.81.E5.88.9D.E5.A7.8B.E5.8C.96">静态初始化</span></h4>
<p>有两种静态初始化的形式：
</p>
<div class="t-li1"><span class="t-li">1)</span> 如果相关，则应用<a href="constant_initialization.html" title="cpp/language/constant initialization">常量初始化</a>。</div>
<div class="t-li1"><span class="t-li">2)</span> 否则非局部静态及线程局域变量会被<a href="zero_initialization.html" title="cpp/language/zero initialization">零初始化</a>。</div>
<p>实践中：
</p>
<ul><li> 常量初始化通常在编译期进行。预先被计算的对象表示会作为程序映像的一部分存储下来。如果编译器没有这样做，那么它仍然必须保证该初始化发生早于任何动态初始化。
</li><li> 零初始化的变量将被置于程序映像的 <code>.bss</code> 段，它不占据磁盘空间，并在加载程序时由操作系统以零填充。
</li></ul>
<h4><span class="mw-headline" id=".E5.8A.A8.E6.80.81.E5.88.9D.E5.A7.8B.E5.8C.96">动态初始化</span></h4>
<p>在所有静态初始化完成后，在下列情形中进行非局部变量的动态初始化：
</p>
<div class="t-li1"><span class="t-li">1)</span> <i>无序的动态初始化</i>，仅适用于未被<a href="template_specialization.html" title="cpp/language/template specialization">显式特化</a>的（静态/线程局域）类模板的<a href="static.html" title="cpp/language/static">静态数据成员</a><span class="t-rev-inl t-since-cxx14"><span>及<a href="variable_template.html" title="cpp/language/variable template">变量模板</a></span> <span><span class="t-mark-rev t-since-cxx14">(C++14 起)</span></span></span>。这些静态变量的初始化相对于所有其他动态初始化之间是顺序不确定的<span class="t-rev-inl t-since-cxx17"><span>，除非程序在初始化某个变量之前开始了一个线程，此时初始化则是无顺序的</span> <span><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></span></span>。这些线程局域变量的初始化相对于所有其他动态初始化之间是无顺序的。</div>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx17"><td>
<div class="t-li1"><span class="t-li">2)</span> <i>部分有序的动态初始化</i>，适用于并未被隐式或显式实例化的特化的所有 inline 变量。如果一个部分有序的 V 在每个翻译单元中比有序或部分有序的 W 更早定义，那么 V 的初始化按顺序早于（或若程序启动了线程，则为先发生于）W 的初始化。</div>
</td>
<td><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></td></tr>
</table>
<div class="t-li1"><span class="t-li">3)</span> <i>有序的动态初始化</i>，适用于所有其他非局部变量：在单个翻译单元中，这些变量的初始化始终严格以其定义出现于源代码中的顺序<a href="eval_order.html" title="cpp/language/eval order">定序</a>。不同翻译单元中的静态变量的初始化之间是顺序不确定的。不同翻译单元中的线程局域变量的初始化之间是无顺序的。</div>
<p>当拥有静态或线程存储期的非局部变量的初始化通过异常退出时，调用 <span class="t-lc"><a href="../error/terminate.html" title="cpp/error/terminate">std::terminate</a></span>。
</p>
<h4><span class="mw-headline" id=".E6.8F.90.E6.97.A9.E5.8A.A8.E6.80.81.E5.88.9D.E5.A7.8B.E5.8C.96">提早动态初始化</span></h4>
<p>在下列条件都满足的情况下，允许编译器将初始化动态初始化的变量作为静态初始化（实为编译期）的一部分：
</p>
<div class="t-li1"><span class="t-li">1)</span> 初始化的动态版本不改变命名空间作用域中任何先于其初始化的对象的值</div>
<div class="t-li1"><span class="t-li">2)</span> 初始化的静态版本在被初始化变量中产生的值，与当所有不要求静态初始化的变量都被动态初始化时，由动态初始化所生成的值相同。</div>
<p>因为上述规则，如果某对象 <code>o1</code> 的初始化涉及到命名空间作用域对象 <code>o2</code>，而它潜在地要求动态初始化，但在同一翻译单元中在其之后定义，那么不指明所用的 <code>o2</code> 是完全初始化的 <code>o2</code> 的值（因为编译器把 <code>o2</code> 的初始化提升到编译时）还是 <code>o2</code> 仅被零初始化的值。
</p>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="kw1">inline</span> <span class="kw4">double</span> fd<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span> <span class="kw1">return</span> <span class="nu16">1.0</span><span class="sy4">;</span> <span class="br0">}</span>
<span class="kw4">extern</span> <span class="kw4">double</span> d1<span class="sy4">;</span>
<span class="kw4">double</span> d2 <span class="sy1">=</span> d1<span class="sy4">;</span>   <span class="co1">// 未指明：</span>
                  <span class="co1">// 如果 d1 被动态初始化则动态初始化为 0.0，或</span>
                  <span class="co1">// 如果 d1 被静态初始化则动态初始化为 1.0，或</span>
                  <span class="co1">// 静态初始化为 0.0（因为当两个变量都被动态初始化时将为这个值）</span>
<span class="kw4">double</span> d1 <span class="sy1">=</span> fd<span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="co1">// 可能静态或动态初始化为 1.0</span></pre></div></div>
<h4><span class="mw-headline" id=".E5.BB.B6.E8.BF.9F.E5.8A.A8.E6.80.81.E5.88.9D.E5.A7.8B.E5.8C.96">延迟动态初始化</span></h4>
<p>动态初始化是发生早于（对于静态变量）主函数或（对于线程局域变量）其线程的首个函数的首条语句，还是延迟到发生晚于它们，是由实现定义的。
</p><p>如果<span class="t-rev-inl t-since-cxx17"><span>非内联变量</span> <span><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></span></span>的初始化延迟到发生晚于主/线程函数的首条语句，那么它发生早于与所初始化的变量定义于同一翻译单元中的任何拥有静态/线程存储期的变量的首次 <a href="definition.html#ODR_.E5.BC.8F.E4.BD.BF.E7.94.A8" title="cpp/language/definition">ODR 式使用</a>。若给定翻译单元中没有 ODR 式使用变量或函数，则定义于该翻译单元的非局部变量可能始终不被初始化（这模仿按需的动态库的行为）。然而，只要翻译单元中 ODR 式使用了任何事物，就会初始化所有在初始化或销毁中拥有副作用的非局部变量，即使程序中没有用到它们。
</p>
 <table class="t-rev-begin">
<tr class="t-rev t-since-cxx17"><td>
<p>如果内联变量的初始化被延迟，那么它发生早于这个特定变量的首次 <a href="definition.html#ODR_.E5.BC.8F.E4.BD.BF.E7.94.A8" title="cpp/language/definition">ODR 式使用</a>。
</p>
</td>
<td><span class="t-mark-rev t-since-cxx17">(C++17 起)</span></td></tr>
</table>
<div dir="ltr" class="mw-geshi" style="text-align: left;"><div class="cpp source-cpp"><pre class="de1"><span class="co1">// - 文件 1 -</span>
<span class="co2">#include "a.h"</span>
<span class="co2">#include "b.h"</span>
B b<span class="sy4">;</span>
A<span class="sy4">::</span><span class="me2">A</span><span class="br0">(</span><span class="br0">)</span><span class="br0">{</span> b.<span class="me1">Use</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span> <span class="br0">}</span>
 
<span class="co1">// - 文件 2 -</span>
<span class="co2">#include "a.h"</span>
A a<span class="sy4">;</span>
 
<span class="co1">// - 文件 3 -</span>
<span class="co2">#include "a.h"</span>
<span class="co2">#include "b.h"</span>
<span class="kw4">extern</span> A a<span class="sy4">;</span>
<span class="kw4">extern</span> B b<span class="sy4">;</span>
 
<span class="kw4">int</span> main<span class="br0">(</span><span class="br0">)</span> <span class="br0">{</span>
    a.<span class="me1">Use</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
    b.<span class="me1">Use</span><span class="br0">(</span><span class="br0">)</span><span class="sy4">;</span>
<span class="br0">}</span>
 
<span class="co1">// 如果 a 在进入 main 之前被初始化，那么 b 可能在 A::A() 使用它的时间点仍未被初始化</span>
<span class="co1">// （因为动态初始化在翻译单元间是顺序不确定的）</span>
 
<span class="co1">// 如果 a 在某个 main 的首条语句之后的时间点初始化</span>
<span class="co1">// （它 ODR 式使用了定义于文件 1 的函数，强制其初始化得以运行），</span>
<span class="co1">// 那么 b 将在 A::A 使用它前初始化</span></pre></div></div>
<h3><span class="mw-headline" id=".E9.9D.99.E6.80.81.E5.B1.80.E9.83.A8.E5.8F.98.E9.87.8F">静态局部变量</span></h3>
<p>有关局部（即块作用域）的静态和线程局部变量，见<a href="storage_duration.html#.E9.9D.99.E6.80.81.E5.B1.80.E9.83.A8.E5.8F.98.E9.87.8F" title="cpp/language/storage duration">静态局部变量</a>。
</p><p>拥有<a href="storage_duration.html#.E8.BF.9E.E6.8E.A5" title="cpp/language/storage duration">外部或内部链接</a>的变量的块作用域声明中不允许初始化器。这种声明必须带 <span class="t-c"><span class="mw-geshi cpp source-cpp"><span class="kw4">extern</span></span></span> 出现而且不能为定义。
</p>
<h3><span class="mw-headline" id=".E7.B1.BB.E6.88.90.E5.91.98">类成员</span></h3>
<p>非静态数据成员可以<a href="initializer_list.html" title="cpp/language/initializer list" class="mw-redirect">成员初始化器列表</a>或以<a href="data_members.html#.E6.88.90.E5.91.98.E5.88.9D.E5.A7.8B.E5.8C.96" title="cpp/language/data members">默认成员初始化器</a>初始化。
</p>
<h3><span class="mw-headline" id=".E6.B3.A8.E8.A7.A3">注解</span></h3>
<p>非局部变量的销毁顺序在 <span class="t-lc"><a href="../utility/program/exit.html" title="cpp/utility/program/exit">std::exit</a></span> 中描述。
</p>
<h3><span class="mw-headline" id=".E5.8F.82.E9.98.85">参阅</span></h3>
<ul><li> <a href="copy_elision.html" title="cpp/language/copy elision"> 复制消除</a>
</li><li> <a href="converting_constructor.html" title="cpp/language/converting constructor"> 转换构造函数</a>
</li><li> <a href="copy_constructor.html" title="cpp/language/copy constructor"> 复制构造函数</a>
</li><li> <a href="default_constructor.html" title="cpp/language/default constructor"> 默认构造函数</a>
</li><li> <a href="explicit.html" title="cpp/language/explicit"><code> explicit</code></a>
</li><li> <a href="move_constructor.html" title="cpp/language/move constructor"> 移动构造函数</a>
</li><li> <a href="new.html" title="cpp/language/new"> new</a>
</li></ul>
<table class="t-dsc-begin">

</table>

<!-- 
NewPP limit report
Preprocessor visited node count: 1797/1000000
Preprocessor generated node count: 5132/1000000
Post‐expand include size: 40568/2097152 bytes
Template argument size: 8380/2097152 bytes
Highest expansion depth: 13/40
Expensive parser function count: 0/100
-->

<!-- Saved in parser cache with key mwiki1-mwiki_zh_:pcache:idhash:8414-0!*!0!!zh!*!zh!* and timestamp 20211022154015 -->
</div>                    <!-- /bodycontent -->
                                        <!-- printfooter -->
                    <div class="printfooter">
                    来自“<a href="https://zh.cppreference.com/mwiki/index.php?title=cpp/language/initialization&amp;oldid=71351">https://zh.cppreference.com/mwiki/index.php?title=cpp/language/initialization&amp;oldid=71351</a>”                    </div>
                    <!-- /printfooter -->
                                                            <!-- catlinks -->
                    <!-- /catlinks -->
                                                            <div class="visualClear"></div>
                    <!-- debughtml -->
                                        <!-- /debughtml -->
                </div>
                <!-- /bodyContent -->
            </div>
        </div>
        <!-- /content -->
        <!-- footer -->
        <div id="cpp-footer-base" class="noprint">
            <div id="footer">
                        <div id="cpp-navigation">
            <h5>导航</h5>
            <ul><li><a href="https://zh.cppreference.com/w/cpp/language/initialization">Online version</a></li><li>Offline version retrieved 2022-01-01 00:37.</li></ul></div>
                        <ul id="footer-info">
                                    <li id="footer-info-lastmod"> 本页面最后修改于2021年7月6日 (星期二) 22:41。</li>
                                    <li id="footer-info-viewcount">此页面已被浏览过31,560次。</li>
                            </ul>
                    </div>
        </div>
        <!-- /footer -->
        <script>if(window.mw){
mw.loader.state({"site":"loading","user":"missing","user.groups":"ready"});
}</script>
<script src="../../../common/skin_scripts.js"></script>
<script>if(window.mw){
mw.loader.load(["mediawiki.action.view.postEdit","mediawiki.user","mediawiki.page.ready","mediawiki.searchSuggest","mediawiki.hidpi","ext.gadget.MathJax","ext.gadget.ColiruCompiler"], null, true);
}</script>
<script src="../../../common/site_scripts.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2828341-1']);
_gaq.push(['_setDomainName', 'cppreference.com']);
_gaq.push(['_trackPageview']);
</script><!-- Served in 0.926 secs. -->
	</body>
<!-- Cached 20211022154015 -->
</html>